package com.atmilan.quartz.utils.source;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.CategoryTypeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.StockAreaTempEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.Discount;
import com.atmilan.quartz.model.entity.buyer.Supplier;
import com.atmilan.quartz.model.entity.carotta.CarottaProduct;
import com.atmilan.quartz.model.entity.carotta.CarottaProductSku;
import com.atmilan.quartz.model.entity.crmeb.CategoryMatch;
import com.atmilan.quartz.model.entity.crmeb.StoreBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.result.PriceResult;
import com.atmilan.quartz.service.ICategoryMatchService;
import com.atmilan.quartz.service.IStoreBrandService;
import com.atmilan.quartz.service.ISupplierService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.sync.push.crmeb.enums.CrmebMerchantEnums;
import com.atmilan.quartz.utils.PriceUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

/**
 * 处理源数据转换和计算相关信息
 * @Description: 
 * @author daigb
 * @date 2021-03-05
 */
@Service
public class SourceCarottaProductUtil {
    @Autowired
    IStoreBrandService storeBrandService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ISupplierService supplierService;
    @Autowired
    PriceUtil priceUtil;

    /**
     *
     * 构建DO对象（CAROTTA）
     * @param product
     * @param skus
     * @return
     */
    public StoreProductCrmebRequest buildCarottaProduct(CarottaProduct product, List<CarottaProductSku> skus,List<Discount> discountList) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = new StoreProductCrmebRequest();
        try {
            // 分类
            List<String> cateList = new ArrayList<>();
            CategoryMatch categoryMatch = null;
            if(StringUtils.isNotBlank(product.getTags())){
                String[] split = product.getTags().split(",");
                cateList = Stream.of(split).map(String::trim).map(String::toUpperCase).collect(Collectors.toList());
                cateList.add("");
                categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                        .eq(CategoryMatch::getType, CategoryTypeEnum.CAROTTA.getCode())
                        .in(CategoryMatch::getOthCategoryId, cateList)
                        .in(CategoryMatch::getOthCategoryName, cateList)
                        .in(CategoryMatch::getOthCategoryType,cateList)
                        .last("LIMIT 1"));
//                categoryMatchService.unMatchCategory(categoryMatch,product.getTags(),null,null,CategoryTypeEnum.CAROTTA);
                // 复制重量
                if(null != categoryMatch) {
                	CategoryMatch supCategoryMatch = categoryMatchService.getById(categoryMatch.getCategoryId());
                	categoryMatch.setWeight(Optional.ofNullable(supCategoryMatch).orElse(new CategoryMatch()).getWeight());
                }
                if(cateList.contains("I90")){
                    productRequest.setSeasonCode("AW19");
                }
                if(cateList.contains("E100")){
                    productRequest.setSeasonCode("SS20");
                }
                if(cateList.contains("I110")){
                    productRequest.setSeasonCode("AW20");
                }
                if(cateList.contains("E120")){
                    productRequest.setSeasonCode("SS21");
                }
                if(cateList.contains("I130")){
                    productRequest.setSeasonCode("AW21");
                }
                if(cateList.contains("E140")){
                    productRequest.setSeasonCode("SS22");
                }
                if (cateList.contains("Carryover")) {
                    productRequest.setSeasonCode("CO");
                }
            }
            // 品牌对应
            StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                    .eq(StoreBrand::getEnName, product.getVendor())
                    .eq(StoreBrand :: getType, ProductTypeEnum.CAROTTA)
                    .last("LIMIT 1")
            );
            storeBrandService.unMatchBrand(buyerStoreBrand,null,product.getVendor(),ProductTypeEnum.CAROTTA);
            StoreBrand storeBrand = null;
            if(null != buyerStoreBrand) {
                if(null != buyerStoreBrand.getSuperId()) {
                    storeBrand = storeBrandService.getById(buyerStoreBrand.getSuperId());
                }
            } else {
                storeBrand = storeBrandService.getById(5429);
            }
            BigDecimal productDiscount = BigDecimal.ZERO;
            //计算该商品折扣
            for (Discount discount : discountList) {
                //sku匹配
                if(discount.getSkuId() != null && discount.getSkuId().equals(skus.get(0).getSku())){
                    productDiscount = discount.getDiscount();
                    break;
                }
                //季节匹配 AW21, SS22, AW20
                if(productRequest.getSeasonCode() == null){
                    break;
                }
                if(discount.getSeason() == null){
                    continue;
                }
                //特殊品牌处理
                if("MAX MARA S".equals(product.getVendor().toUpperCase())){
                    product.setVendor("MAX MARA");
                }
                if("DSQUARED2".equals(product.getVendor().toUpperCase())){
                    product.setVendor("DSQUARED");
                }
                if (productRequest.getSeasonCode().equals(discount.getSeason()) && discount.getBrand().toUpperCase().equals(product.getVendor().toUpperCase())) {
                    if (!"RTW".equals(discount.getCate()) && product.getTags().toUpperCase().contains(discount.getCate())) {
                        if (StringUtils.isNotBlank(discount.getName())) {
                            if (product.getTitle().toUpperCase().contains(discount.getName().toUpperCase())) {
                                productDiscount = discount.getDiscount();
                                break;
                            }
                        } else {
                            productDiscount = discount.getDiscount();
                            break;
                        }
                    } else if ("RTW".equals(discount.getCate()) && !(product.getTags().toUpperCase().contains("SHOES") || product.getTags().toUpperCase().contains("BAG") || product.getTags().toUpperCase().contains("ACCESSORIES"))) {
                        if (StringUtils.isNotBlank(discount.getName())) {
                            if (product.getTitle().toUpperCase().contains(discount.getName().toUpperCase())) {
                                productDiscount = discount.getDiscount();
                                break;
                            }
                        } else {
                            productDiscount = discount.getDiscount();
                            break;
                        }
                    }
                }
            }
//            BigDecimal compareAtPrice = skus.stream().filter(e->null != e.getCompareAtPrice()).map(CarottaProductSku::getCompareAtPrice).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
//            BigDecimal otPrice = PriceUtil.eur2Rmb(skus.stream().map(CarottaProductSku::getPrice).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO));
            BigDecimal otPrice = skus.stream().map(CarottaProductSku::getPrice).min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
            BigDecimal discount = new BigDecimal(100).subtract(productDiscount).movePointLeft(2);
            PriceResult priceResult = priceUtil.eur2Rmb(otPrice);
            BigDecimal price = priceResult.getPrice().multiply(discount).divide(BigDecimal.valueOf(1.22),0,BigDecimal.ROUND_UP);
            /***** 处理对象构建 *******/
            String barCode = BarCodeEnum.CAROTTA.getCode() + product.getProductId().toString();
            List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<StoreProductAttrValueRequest>();

            List<String> colorValueList = new ArrayList<>();
            List<String> sizeValueList = new ArrayList<>();
            // 规格
            StoreProductAttr storeProductAttr = new StoreProductAttr();
            storeProductAttr.setAttrName("尺寸");
            storeProductAttr.setType(0);
            storeProductAttr.setBarCode(barCode);
            // 颜色
            StoreProductAttr storeProductAttrColor = new StoreProductAttr();
            storeProductAttrColor.setAttrName("颜色");
            storeProductAttrColor.setType(0);
            storeProductAttrColor.setBarCode(barCode);

            for(CarottaProductSku sku : skus) {
                // 售价
//                BigDecimal adjustPrice = PriceUtil.eur2Rmb(sku.getPrice());
                BigDecimal erpPrice = sku.getPrice();
                // 成本价
//                BigDecimal erpPrice = sku.getCompareAtPrice();
                BigDecimal adjustPrice =priceUtil.eur2Rmb(erpPrice).getPrice().multiply(discount).divide(BigDecimal.valueOf(1.22),0,BigDecimal.ROUND_UP);
                // value对象
                StoreProductAttrValueRequest storeProductAttrValue = new StoreProductAttrValueRequest();
                storeProductAttrValue.setSourceSkuId(sku.getSkuId().toString());
                storeProductAttrValue.setStock(sku.getInventoryQuantity());
                storeProductAttrValue.setPrice(adjustPrice);
                storeProductAttrValue.setImage(product.getImage());
                storeProductAttrValue.setCost(adjustPrice);
                storeProductAttrValue.setSourceCost(adjustPrice);
                storeProductAttrValue.setBarCode(barCode);
                storeProductAttrValue.setOtPrice(erpPrice);
                //发货地（欧洲）
                storeProductAttrValue.setTempId(StockAreaTempEnum.EUR.getTempId());
                List<String> suk = new ArrayList<>();
                LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                if (StringUtils.isNotBlank(sku.getColor())) {
                    linkedMap.put("颜色", sku.getColor());
                    if(!colorValueList.contains(sku.getColor())){
                        colorValueList.add(sku.getColor());
                    }
                    suk.add(sku.getColor());
                }
                if (StringUtils.isNotBlank(sku.getSize())) {
                    linkedMap.put("尺寸", sku.getSize());
                    if(!sizeValueList.contains(sku.getSize())){
                        sizeValueList.add(sku.getSize());
                    }
                    suk.add(sku.getSize());
                }
                //suk
                storeProductAttrValue.setSuk(String.join(",", suk));
                storeProductAttrValue.setAttrValue(linkedMap);
                attrValueList.add(storeProductAttrValue);
            }
            //attr对象
            if (CollectionUtils.isNotEmpty(colorValueList)) {
                storeProductAttrColor.setAttrValues(String.join(",", colorValueList));
                attrList.add(storeProductAttrColor);
            }
            if (CollectionUtils.isNotEmpty(sizeValueList)) {
                storeProductAttr.setAttrValues(String.join(",", sizeValueList));
                attrList.add(storeProductAttr);
            }

            productRequest.setExchangeRate(priceResult.getExchangeRate());
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            // 强制写一个 商户id 作为buyer商品标识标识
            productRequest.setMerId(CrmebMerchantEnums.CAROTTA.getMerchantId());
            productRequest.setContent(product.getBodyHtml());
            // 国际公码
            productRequest.setKeyword(skus.get(0).getSku());
//            productRequest.setStoreInfo(product.getHandle());
            productRequest.setStoreInfo(product.getBodyHtml());
            productRequest.setStoreName(product.getTitle());
            if(null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(price);
            productRequest.setOtPrice(otPrice);
            productRequest.setCost(price);
            productRequest.setSourceCost(price);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            productRequest.setTempId(3);

            // 供应商
            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                    .eq(Supplier :: getBarcode, BarCodeEnum.CAROTTA.getCode())
                    .last("LIMIT 1")
            );
            if(null != supplier) {
                productRequest.setSuppliersId(supplier.getId());
                productRequest.setSuppliersName(supplier.getSuppliersName());
            }
            productRequest.setBarCode(barCode);
            // 分类
            Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 1859;
            productRequest.setCateId(categoryId);
            productRequest.setCateIds(Arrays.asList(categoryId));
            productRequest.setWeight(null != categoryMatch ? categoryMatch.getWeight() : BigDecimal.ONE);
            
            // 轮播图
            List<String> sliderImage = new ArrayList<>();
            sliderImage.add(product.getImage());
            sliderImage.addAll(JSONArray.parseArray(product.getImages()).toJavaList(String.class));
            
            productRequest.setImage(product.getImage());
            productRequest.setSliderImage(JSONArray.toJSONString(sliderImage));
            productRequest.setIsShow(true);
            productRequest.setSpecType(true);
            productRequest.setIsEurope(ProductTypeEnum.CAROTTA.getCode());
            productRequest.setUnitName("件");
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return productRequest;

    }

}
